import qs from 'qs';

const defaultConfig = {
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
  responseType: 'JSON',
};

const request = (url, options) => {
  if (typeof url !== 'string') throw new TypeError('url必须是字符串');
  const requestUrl = '/api' + url;
  const config = { ...defaultConfig, ...options, };
  const { responseType, } = config;
  const token = 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImVmY2YzNTBjLTVmYmMtNDM0Yi1hMmE4LWJkNzRmNjllOWJjZCJ9.VtZebIwKJavJPqYaPcEj941ILGs7gb0fy5rcetnzOj9gBQUo_zmHMDclS0acH5I736oaZ1XZQ4W__T1MtnJ_ZA';
  if (token) {
    config.headers.Authorization = 'Bearer ' + token;
  }
  return fetch(requestUrl, config)
    .then((res) => {
      if (!res.ok) {
        throw new Error('接口请求异常');
      }
      // 判断返回数据类型
      let result;
      switch (responseType.toUpperCase()) {
        case 'JSON':
          result = res.json();
          break;
        case 'TEXT':
          result = res.text();
          break;
        case 'FORMDATA':
          result = res.formData();
          break;
        case 'BLOB':
          result = res.blob();
          break;
        case 'ARRAYBUFFER':
          result = res.arrayBuffer();
          break;
        default:
          result = res.json();
          break;
      }
      return result;
    })
    .then((data) => {
      const code = data.code;
      const message = data.msg;
      if (code === 200) {
        return data;
      } else {
        return Promise.reject(new Error(message));
      }
    });
};

export function get(url, data, config) {
  if (typeof url !== 'string') throw new TypeError('url必须是字符串');
  if (data) {
    const params = qs.stringify(data);
    url += url.includes('?') ? `&${params}` : `?${params}`;
  }
  return request(url, {
    method: 'GET',
    ...config,
  });
}

export function post(url, data, config) {
  let body = null;
  if (data) {
    const contentType = config?.headers['Content-Type'];
    body = contentType?.includes('x-www-form-urlencoded')
      ? qs.stringify(data)
      : JSON.stringify(data);
  }
  return request(url, {
    method: 'POST',
    body,
    ...config,
  });
}

export function put(url, data, config) {
  let body = null;
  if (data) {
    const contentType = config?.headers['Content-Type'];
    body = contentType?.includes('x-www-form-urlencoded')
      ? qs.stringify(data)
      : JSON.stringify(data);
  }
  return request(url, {
    method: 'PUT',
    body,
    ...config,
  });
}

export function del(url, data, config) {
  let body = null;
  if (data) {
    const contentType = config?.headers['Content-Type'];
    body = contentType?.includes('x-www-form-urlencoded')
      ? qs.stringify(data)
      : JSON.stringify(data);
  }
  return request(url, {
    method: 'DELETE',
    body,
    ...config,
  });
}
